﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HPIT.RentHouse.Common;
using HPIT.RentHouse.DTO;
using HPIT.RentHouse.IService;
using HPIT.RentHouse.Service.Entities;
using HPIT.RentHouse.Redis;

namespace HPIT.RentHouse.Service
{
    public class HouseService : IHouseService
    {
        /// <summary>
        /// 获取房源列表
        /// </summary>
        /// <param name="communityName"></param>
        /// <param name="typeId"></param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<HouseDTO> GetHouseList(string communityName, int start, int length, ref int totalCount)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_Houses>(db);
            var query = PredicateExtensions.True<T_Houses>();
            if (!string.IsNullOrWhiteSpace(communityName))
            {
                query = query.And(e => e.T_Communities.Name.Contains(communityName));
            }
            var list = bs.GetPagedList(start, length, ref totalCount, query, a => a.Id);
            var result = list.Select(a => new HouseDTO
            {
                Id = a.Id,
                RegionName = a.T_Communities.T_Regions.Name,
                CommunityName = a.T_Communities.Name,
                Address = a.Address,
                MonthRent = a.MonthRent,
                RoomTypeName = a.T_IdNames3.Name,
                DecorateStatus = a.T_IdNames.Name,
                Area = a.Area,
            }).ToList();
            return result;
        }

        /// <summary>
        /// 获取房源附属设施
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<AttachmentDTO> GetAttachmentList()
        {
            var db = new RentEntity();
            var bs = new BaseService<T_Attachments>(db);
            var list = bs.GetList(h => true).Select(e => new AttachmentDTO
            {
                Id = e.Id,
                Name = e.Name,
                IconName = e.IconName
            }).ToList();
            return list;
        }
        /// <summary>
        /// 添加房源
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public AjaxResult AddHouse(HouseAddDTO dto)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_Houses>(db);
            var bsAttachment = new BaseService<T_Attachments>(db);
            //添加房源信息
            var model = new T_Houses();
            model.CommunityId = dto.CommunityId;
            model.RoomTypeId = dto.RoomTypeId;
            model.Address = dto.Address;
            model.MonthRent = dto.MonthRent;
            model.StatusId = dto.StatusId;
            model.Area = dto.Area;
            model.DecorateStatusId = dto.DecorateStatusId;
            model.TotalFloorCount = dto.TotalFloorCount;
            model.FloorIndex = dto.FloorIndex;
            model.TypeId = dto.TypeId;
            model.Direction = dto.Direction;
            model.LookableDateTime = dto.LookableDateTime;
            model.CheckInDateTime = dto.CheckInDateTime;
            model.OwnerName = dto.OwnerName;
            model.OwnerPhoneNum = dto.OwnerPhoneNum;
            model.Description = dto.Description;
            model.CreateDateTime = DateTime.Now;
            model.IsDeleted = false;

            //添加房屋配套设施
            //给关联表(T_AttachmentIds添加数据)  先判断关联表中是否存在数据，存在则添加
            if (dto.AttachmentIds != null && dto.AttachmentIds.Count > 0)
            {
                foreach (var id in dto.AttachmentIds)
                {
                    T_Attachments attachments = bsAttachment.Get(a => a.Id == id);
                    model.T_Attachments.Add(attachments);
                }
            }
            if (bs.Add(model) > 0)
            {
                return new AjaxResult(ResultState.Success, "房源信息添加成功");
            }
            else
            {
                return new AjaxResult(ResultState.Error, "房源信息添加失败");
            }
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public AjaxResult AddPic(HousePicDTO dto)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_HousePics>(db);
            var model = new T_HousePics()
            {
                HouseId = dto.HouseId,
                Url = dto.Url,
                ThumbUrl = dto.ThumbUrl,
                CreateDateTime = DateTime.Now,
                IsDeleted = false
            };
            if (bs.Add(model) > 0)
            {
                return new AjaxResult(ResultState.Success, "上传成功");
            }
            else
            {
                return new AjaxResult(ResultState.Error, "上传失败");
            }
        }
        /// <summary>
        /// 查看图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<HousePicDTO> GetHousePics(long lookid)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_HousePics>(db);
            var list = bs.GetList(a => a.HouseId == lookid).Select(e => new HousePicDTO()
            {
                Id = e.Id,
                HouseId = e.HouseId,
                Url = e.Url,
                ThumbUrl = e.ThumbUrl
            }).ToList();
            return list;
        }
        /// <summary>
        /// 批量删除图片
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public AjaxResult DeleteBatchPics(List<long> picId)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_HousePics>(db);
            //通过循环获取用户选中的多个图片id,并查询这批数据，实现批量删除
            foreach (var id in picId)
            {
                var model = bs.Get(a => a.Id == id);
                //执行删除
                bs.Delete(model);
            }
            return new AjaxResult(ResultState.Success, "删除图片成功！");
        }
        /// <summary>
        /// 删除房源
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult Delete(long id)
        {
            var db = new RentEntity();
            BaseService<T_Houses> bs = new BaseService<T_Houses>(db);
            //根据id查询该条数据是否存在
            var model = bs.Get(a => a.Id == id);
            if (bs.Delete(model))
            {
                return new AjaxResult(ResultState.Success, "删除房源成功！");
            }
            else
            {
                return new AjaxResult(ResultState.Error, "删除房源失败！");
            }
        }
        /// <summary>
        /// 批量删除房源
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public AjaxResult DeleteBatch(List<long> ids)
        {
            try
            {
                var db = new RentEntity();
                BaseService<T_Houses> bs = new BaseService<T_Houses>(db);
                //通过循环获取用户选中的多个id,并查询这批数据，实现批量删除
                foreach (var id in ids)
                {
                    var model = bs.Get(a => a.Id == id);
                    bs.Delete(model);
                }
                return new AjaxResult(ResultState.Success, "批量删除成功！");
            }
            catch (Exception)
            {
                return new AjaxResult(ResultState.Error, "批量删除失败！");
            }
        }
        /// <summary>
        /// 获取房源列表信息(前端页面展示)
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="cityId"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<HouseDTO> GetHouseList(int pageIndex, int cityId, int pageSize)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_Houses>(db);
            var query = PredicateExtensions.True<T_Houses>();
            if (cityId > 0)
            {
                query = query.And(e => e.T_Communities.T_Regions.CityId == cityId);
            }
            int rowCount = 0;
            int start = (pageIndex - 1) * pageSize;

            var list = bs.GetPagedList(start, pageSize, ref rowCount, query, e => e.Id, false).Select(e => new HouseDTO
            {
                Id = e.Id,
                Address = e.Address,
                Area = e.Area,
                CommunityName = e.T_Communities.Name,
                MonthRent = e.MonthRent,
                DecorateStatusId = e.DecorateStatusId,
                RoomTypeId = e.RoomTypeId,
                RoomTypeName = e.T_Communities.T_Regions.Name,
                FirstThumbUrl = e.T_HousePics.Where(a=>!a.IsDeleted).FirstOrDefault().ThumbUrl
            }).ToList();
            var IdNames = new BaseService<T_IdNames>(db);
            var idNamesList = IdNames.GetList(a => true).ToList();

            //foreach循环获取每个对象的房间类型和装修类型
            list.ForEach(a =>
            {
                a.DecorateStatus = idNamesList.Where(e => e.Id == a.DecorateStatusId).FirstOrDefault().Name;
                a.RoomTypeName = idNamesList.Where(e => e.Id == a.RoomTypeId).FirstOrDefault().Name;
            });
            return list;
        }
        /// <summary>
        /// 根据条件搜索符合条件的房源信息
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public List<HouseDTO> Search(HouseSearchOptions options)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_Houses>(db);

            //默认显示当前城市的房源
            var query = bs.GetList(e => e.T_Communities.T_Regions.CityId == options.CityId);
            //如果区域>0，则按照区域进行检索
            if (options.RegionId > 0)
            {
                query = query.Where(e => e.T_Communities.RegionId == options.RegionId);
            }
            //按租金检索
            if (options.StartMonthRent.HasValue)
            {
                query = query.Where(e => e.MonthRent >= options.StartMonthRent.Value);
            }
            if (options.EndMonthRent.HasValue)
            {
                query = query.Where(e => e.MonthRent <= options.EndMonthRent.Value);
            }

            //按照关键字检索，若关键字不为空
            if (!string.IsNullOrEmpty(options.Keywords))
            {
                query = query.Where(e => e.Address.Contains(options.Keywords) || e.Description.Contains(options.Keywords));
            }

            //排序
            switch (options.OrderByType)
            {
                case "MonthRentAsc":
                    query = query.OrderBy(e => e.MonthRent);
                    break;
                case "MonthRentDesc":
                    query = query.OrderByDescending(e => e.MonthRent);
                    break;
                case "AreaAsc":
                    query = query.OrderBy(e => e.Area);
                    break;
                case "AreaDesc":
                    query = query.OrderByDescending(e => e.Area);
                    break;
                default:
                    query = query.OrderByDescending(e => e.Id);
                    break;
            }

            var list = query.Select(a => new HouseDTO()
            {
                Id = a.Id,
                Area = a.Area,
                CommunityName = a.T_Communities.Name,
                MonthRent = a.MonthRent,
                FirstThumbUrl = a.T_HousePics.Where(e => !e.IsDeleted).FirstOrDefault().ThumbUrl,
                RoomTypeId = a.RoomTypeId,
                DecorateStatusId = a.DecorateStatusId
            }).ToList();

            var bsl = new BaseService<T_IdNames>(db);
            //foreach循环获取每个对象的房间类型和装修类型
            list.ForEach(e =>
            {
                e.RoomTypeName = bsl.Get(a => a.Id == e.RoomTypeId).Name;
                e.DecorateStatus = bsl.Get(a => a.Id == e.DecorateStatusId).Name;
            });
            return list;
        }
        /// <summary>
        /// 房源详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public HouseDetailDTO GetHouseDetail(long id)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_Houses>(db);

            //根据id先从redis中查询，如果redis中有数据则直接返回redis中的数据
            //RedisHelper redis = new RedisHelper();
            //var dtoRedis = redis.HashGet<HouseDetailDTO>("housedetail", id.ToString());
            //if (dtoRedis != null)
            //{
            //    return dtoRedis;
            //}

            var bsIdNames = new BaseService<T_IdNames>(db);
            //否则再读取数据库中的数据，并且添加到Redis中
            var model = bs.Get(a => a.Id == id);
            if (model != null)
            {
                var Info = new HouseDetailDTO()
                {
                    Id = model.Id,
                    Address = model.Address,
                    Area = model.Area,
                    CommunityName = model.T_Communities.Name,
                    MonthRent = model.MonthRent,
                    RegionName = model.T_Communities.T_Regions.Name,
                    LocationName = model.T_Communities.Location,
                    CheckInDateTime = model.CheckInDateTime,
                    CommunityBuiltYear = (int)model.T_Communities.BuiltYear,
                    CommunityTraffic = model.T_Communities.Traffic,
                    DecorateStatus = bsIdNames.Get(a => a.Id == model.DecorateStatusId).Name,
                    Description = model.Description,
                    Direction = model.Direction,
                    FloorIndex = model.FloorIndex,
                    LookableDateTime = model.LookableDateTime,
                    RoomTypeName = bsIdNames.Get(a => a.Id == model.RoomTypeId).Name,
                    StatusName = bsIdNames.Get(a => a.Id == model.StatusId).Name,
                    TotalFloorCount = model.TotalFloorCount,
                    TypeName = bsIdNames.Get(a => a.Id == model.TypeId).Name
                };

                //配置设施
                Info.Attachments = new List<AttachmentDTO>();
                foreach (var item in model.T_Attachments)
                {
                    var attachment = new AttachmentDTO()
                    {
                        IconName = item.IconName,
                        Id = item.Id,
                        Name = item.Name
                    };
                    Info.Attachments.Add(attachment);
                }

                //房源图片
                Info.HousePics = new List<HousePicDTO>();
                BaseService<T_HousePics> bsHousePic = new BaseService<T_HousePics>(db);
                var picList = bsHousePic.GetList(e => e.HouseId == id).ToList();
                picList.ForEach(e =>
                {
                    var housePic = new HousePicDTO()
                    {
                        HouseId = e.HouseId,    
                        Id = e.Id,  
                        ThumbUrl = e.ThumbUrl,  
                        Url = e.Url
                    };
                });

                //相似房源
                Info.OtherHouses = bs.GetList(e => e.CommunityId == model.CommunityId).Take(3).Select(e => new HouseDTO()
                {
                    Id = e.Id,
                    Area = e.Area,  
                    CommunityName=e.T_Communities.Name,
                    MonthRent=e.MonthRent,  
                    FirstThumbUrl=e.T_HousePics.FirstOrDefault().ThumbUrl,
                    RoomTypeId=e.RoomTypeId,    
                    DecorateStatusId=e.DecorateStatusId
                }).ToList();

                Info.OtherHouses.ForEach(e =>
                {
                    e.DecorateStatus = bsIdNames.Get(a => a.Id == e.DecorateStatusId).Name;
                    e.RoomTypeName = bsIdNames.Get(a => a.Id == e.RoomTypeId).Name;
                });

                return Info;
            }
            return null;    
        }
    }
}
